var log = require('../util/logger.js');



var mysql = require('mysql');
var config = {
    host: 'localhost',
    port: 3306,
    user: 'kanjia',
    password: 'kYDwmtS4zDkekKie',
    database: 'kanjia',
    charset: 'UTF8MB4_GENERAL_CI'
}
var pool = mysql.createPool(config);

//异步查询
var asynquery = function (sql, values, callback) {
    pool.getConnection(function (err, conn) {
        if (err) {
            log.error(err);
            callback(err, null, null);
        } else {
            conn.query(sql, values, function (qerr, vals, fields) {
                //释放连接
                conn.release();
                //事件驱动回调
                callback(qerr, vals, fields);
            });
        }
    });
};
//同步查询
function query(sql, values) {
    // 返回一个 Promise
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                log.error(err);
                reject(err);
            } else {
                connection.query(sql, values, (err, rows) => {

                    if (err) {
                        log.error(err);
                        reject(err)
                    } else {

                        resolve(rows)
                    }
                    // 结束会话
                    connection.release()
                })
            }
        })
    })
}
function execute(sql, values) {
    // 返回一个 Promise
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                log.error(err);
                reject(err);
            } else {
                connection.query(sql, values, (err, rows) => {

                    if (err) {
                        log.error(err);
                        var error = {
                            code: 500,
                            msg: err
                        }
                        resolve(error)
                    } else {
                        var data = {
                            code: 200,
                            msg: rows
                        }
                        resolve(data)
                    }
                    // 结束会话
                    connection.release()
                })
            }
        })
    })
}

//暴露方法需要加上{} 不加{}是指暴露属性

module.exports = { asynquery, query, config, execute };



